import datetime

from rest_framework.generics import GenericAPIView
from rest_framework.response import Response

from aijia_project.utils.Error_statuscode import ErrorCode
from houses.models import House
from orders.models import Order


# /api/v1.0/user/orders
class OrderViews(GenericAPIView):

    def get(self, request):

        role = request.GET.get('role')
        user = request.user
        user_id = user.id
        # 分别获取我的订单和客户订单的查询集
        if role == 'custom':
            # 我的订单
            orders = Order.objects.filter(user_id=user_id)
        else:
            # 客户订单
            house_set = House.objects.filter(user_id=user_id)
            orders = []
            for house in house_set:
                orders.extend(Order.objects.filter(house=house))
        ORDER_STATUS_ENUM = {
            0: "WAIT_ACCEPT",  # 待接单,
            1: "WAIT_PAYMENT",  # 待支付
            2: "PAID",  # 已支付
            3: "WAIT_COMMENT",  # 待评价
            4: "COMPLETE",  # 已完成
            5: "CANCELED",  # 已取消
            6: "REJECTED"  # 已拒单
        }

        order_list = []
        for order in orders:
            order_info_dict = {
                "amount": order.amount,
                "comment": order.comment,
                "ctime": order.create_time,
                "days": order.days,
                "end_date": order.end_date,
                "img_url": order.house.index_image_url,
                "order_id": order.id,
                "start_date": order.begin_date,
                "status": ORDER_STATUS_ENUM[order.status],
                "title": order.house.title
            }
            order_list.append(order_info_dict)
        data = {
            "data": {
                "orders": order_list
            },
            "errmsg": "OK",
            "errno": ErrorCode.OK
        }
        return Response(data)

    def post(self, request):
        params = request.data
        start_date = params.get('start_date')
        end_date = params.get('end_date')
        house_id = params.get('house_id')

        user = request.user

        start_time = datetime.datetime.strptime(start_date, "%Y-%m-%d")
        end_time = datetime.datetime.strptime(end_date, "%Y-%m-%d")
        timediff = end_time - start_time
        days = timediff.days

        house = House.objects.get(id=house_id)
        house_price = house.price
        amount = house_price * days
        try:
            order_houses = Order.objects.filter(house_id=house_id)
        except Exception as e:
            order = Order.objects.create(house_id=house_id,
                                         begin_date=start_date,
                                         end_date=end_date,
                                         user_id=user.id,
                                         days=days,
                                         house_price=house_price,
                                         amount=amount)
            content = {
                "data": {
                    "order_id": order.id
                },
                "errno": "0",
                "errmsg": "下单成功"
            }
            return Response(content)
        else:

            for order_house in order_houses:
                if order_house.status not in [4, 6]:
                    if order_house.end_date.strftime("%Y-%m-%d") >= start_date >= order_house.begin_date.strftime(
                            "%Y-%m-%d") or order_house.end_date.strftime(
                        "%Y-%m-%d") >= end_date >= order_house.begin_date.strftime("%Y-%m-%d"):
                        return Response({
                            "errno": "4103",
                            "errmsg": "该时间段已经被预定"
                        })
            else:
                order = Order.objects.create(house_id=house_id,
                                             begin_date=start_date,
                                             end_date=end_date,
                                             user_id=user.id,
                                             days=days,
                                             house_price=house_price,
                                             amount=amount)
                content = {
                    "data": {
                        "order_id": order.id
                    },
                    "errno": "0",
                    "errmsg": "下单成功"
                }
                return Response(content)


class AcceptOrRejectOrder(GenericAPIView):

    def put(self, request, order_id):
        params = request.data
        action = params.get('action')
        reason = params.get('reason')

        try:
            order = Order.objects.get(id=order_id)
            if action == 'accept':
                order.status = 3
            else:
                order.status = 6
                order.comment = reason
            order.save()
        except Exception as e:
            data = {
                "errno": "4004",
                "errmsg": "数据错误"
            }
        else:
            data = {
                "errno": "0",
                "errmsg": "操作成功"
            }
        finally:
            return Response(data)


class OrderComment(GenericAPIView):

    def put(self, request, order_id):
        params = request.data
        comment = params.get('comment')

        try:
            order = Order.objects.get(id=order_id)
            order.comment = comment
            order.status = 4
            order.save()
        except Exception as e:
            data = {
                "errno": ErrorCode.DATAERR,
                "errmsg": "数据错误"
            }
        else:
            data = {
                "errno": ErrorCode.OK,
                "errmsg": "评论成功"
            }
        finally:
            return Response(data)
